#include "ll.h"
#include <stdlib.h>
#include <string.h>

void ll_init(LL *pLL) {
	pLL->head = pLL->tail = pLL->current = NULL;
	pLL->numNodes= 0;
}

int ll_insert(LL* ll, LL_Node* node) {
	if (ll->tail == NULL) { //empty
		ll->tail = ll->head = node;
        node->prev = node->next = NULL;
	}
	else {
		ll->tail->next = node;
		node->prev = ll->tail;
        node->next = NULL;
		ll->tail = node;
	}
	ll->numNodes++;
	return 1;
}

void ll_moveFirst(LL* ll) {
	ll->current = ll->head;
}

int ll_moveNext(LL* ll) {
	if (ll->current != NULL ) {
		ll->current = ll->current->next;
	}
}

LL_Node* ll_removeNode(LL* ll, LL_Node* node) {
    if (ll->tail == NULL) {
        return NULL;
    }

    if (node->prev != NULL) {
		(node->prev)->next = (node->next);
	}
	if (node->next != NULL) {
		(node->next)->prev = (node->prev);
	}
	if (ll->head == node) {
		ll->head = node->next;
	}
	if (ll->tail == node) {
		ll->tail = node->prev;
	}

    ll->numNodes--;
	return node;
}


int main(int argc,char** argv) {
	LL ll;
	LL_Node* node;
	int i = 0;

	ll_init(&ll);

	for (i = 0; i < 10; i++) {
		node = (LL_Node*)malloc(sizeof(LL_Node));	
		node->data = i;
		ll_insert(&ll, node);
	}

    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("\n");

    node = ll.head;
    ll_removeNode(&ll, node);
    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("count=%d \n\n", ll.numNodes);

    node = ll.tail;
    ll_removeNode(&ll, node);
    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("count=%d \n\n", ll.numNodes);
    
    node = ll.head;
    node = node->next;
    node = node->next;
    node = node->next;
    printf("delete %d\n", (unsigned int)node->data);
    ll_removeNode(&ll, node);
    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("count=%d \n\n", ll.numNodes);

    printf("deleting all...\n");
    while(ll.tail) {
        ll_removeNode(&ll, ll.tail);
    }
    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("count=%d \n\n", ll.numNodes);

    for (i = 0; i < 10; i++) {
		node = (LL_Node*)malloc(sizeof(LL_Node));	
		node->data = i;
		ll_insert(&ll, node);
	}
    node = ll.head;
    while(node != NULL) {
        printf("node data=%d\n", (unsigned int)node->data);
        node = node->next;
    }
    printf("count=%d \n\n", ll.numNodes);

}
